package com.atguigu.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.order.bean.Order;
import com.atguigu.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

// @RequestMapping("/api/order")
@Slf4j
@RestController
public class OrderController {

    @Autowired
    OrderService orderService;

    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId, @RequestParam("productId") Long productId) {
        System.out.println("userId = " + userId);
        return orderService.createOrder(productId, userId);
    }

    @SentinelResource(value = "seckill-order",fallback = "seckillFallback")
    @GetMapping("/seckill")
    public Order seckill(@RequestParam("userId") Long userId, @RequestParam("productId") Long productId) {
        System.out.println("seckill  ");
        productId = Long.MAX_VALUE;
        return orderService.createOrder(productId, userId);
    }

    public Order seckillFallback(Long userId, Long productId, Throwable  exception) {
        System.out.println("seckillFallback  ");
        Order order = new Order();
        order.setId(userId);
        order.setAddress(exception.getClass().getName());
        return order;
    }

    @GetMapping("/writeDb")
    public String writeDb() {
        return "writeDb...";
    }

    @GetMapping("/readDb")
    public String readDb() {
        log.info("readDb...");
        return "readDb...";
    }
}
